﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class tabpage : MonoBehaviour {

    public bool tabsValid = true;

    public GameObject tabsParent = null;
    public GameObject pagesParent = null;

    public GameObject shade = null;

    protected List<Toggle> liTabs = new List<Toggle>();
    protected List<GameObject> liPages = new List<GameObject>();

	// Use this for initialization
	void Start () {
        ReInit();
	}

    public void ReInit()
    {
        liTabs.Clear();
        liPages.Clear();

        shade.SetActive(tabsValid);

        for( int i = 0; i < tabsParent.transform.childCount; i++ )
        {
            Toggle tog = tabsParent.transform.GetChild(i).gameObject.GetComponent<Toggle>();
            tog.gameObject.name = i.ToString();
            tog.onValueChanged.RemoveAllListeners();
            tog.onValueChanged.AddListener((ison) => {
                if (ison)
                    OnChosen(tog);
                    });
            liTabs.Add(tog);
        }

        for(int i = 0; i < pagesParent.transform.childCount; i++ )
        {
            GameObject g = pagesParent.transform.GetChild(i).gameObject;
            liPages.Add(g);
        }

        if (liTabs.Count > 0)
            liTabs[0].isOn = true;
    }

    void OnChosen( Toggle sender )
    {
        string i = sender.gameObject.name;
        int idx = Convert.ToInt32(i);
        Tab(idx);
    }

    void Tab(int idx)
    {
        if (idx >= liTabs.Count)
            return;

        if (idx >= liPages.Count)
            return;

        for(int i = 0; i < liPages.Count; i++ )
        {
            if (i == idx)
                liPages[i].SetActive(true);
            else
                liPages[i].SetActive(false);

        }
    }

    public void PullTab( int idx )
    {
        liTabs[idx].isOn = true;
    }

    public int GetNowIdx()
    {
        for( int i =0;i < liTabs.Count; i++ )
        {
            if (liTabs[i].isOn)
                return i;
        }

        return -1;
    }

    public int GetNextIdx()
    {
        int nowidx = GetNowIdx();
        if (nowidx < 0)
            return -1;

        int nextidx = nowidx+1;
        if (nextidx >= liTabs.Count)
            return nowidx;
        else
            return nextidx;
    }

    public int GetLastIdx()
    {
        int nowidx = GetNowIdx();
        if (nowidx < 0)
            return -1;

        int nextidx = nowidx-1;
        if (nextidx < 0 )
            return nowidx;
        else
            return nextidx;
    }

    public int GetTabCount()
    {
        return liTabs.Count;
    }

    // Update is called once per frame
    void Update () {
		
	}



}
